def test(fn):
= ["eat","tea","tan","ate","nat","bat"]
strs = [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
expected
= fn(strs)
actual assert sorted(actual) == sorted(expected)
Problem Source: Leetcode
Problem Description
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
tests
Solution
- Time Complexity:
O(m * n)
- Space Complexity:
O(n)
Where m
is the average length of the strings in strs
, and n
is the length of strs
from typing import List
from collections import defaultdict
def groupAnagrams(strs: List[str]) -> List[List[str]]:
= defaultdict(list)
grouped_anagrams
for s in strs:
# key[0] represents a, key[1] represents b, etc.
# key is an array of character counts
= [0]*26
key for c in s:
# use unicode to calculate index location in key that corresponds to c and increment
ord(c) - ord('a')] += 1
key[
# list can't be key, so convert key to tuple for usage with dict
tuple(key)].append(s)
grouped_anagrams[
return grouped_anagrams.values()
test(groupAnagrams)